package com.vehicle_demo.utils;

import java.util.Map;

/**
 * @Author: lxh
 * @name: WarnUtils
 * Date: 2024/6/18  12:54
 */
public class WarnUtils {

    /**
     * 根据预警规则计算预警等级
     * @param signalData 信号数据的Map对象
     * @param warningRule 预警规则的字符串表示
     * @return 预警等级
     */
    public static int calculateWarnLevel(Map<String, Object> signalData, String warningRule) {
        // 解析预警规则并进行计算
        String[] rules = warningRule.split("\\s*;\\s*");
        for (String rule : rules) {
            String[] parts = rule.split("\\s*,\\s*");
            String condition = parts[0].trim();
            int level = Integer.parseInt(parts[1].trim().split("报警等级：")[1].trim());
            if (evaluateCondition(signalData, condition)) {
                return level;
            }
        }

        return -1; // 如果没有匹配的规则，返回默认的预警等级
    }

    /**
     * 根据给定的条件评估信号值
     * @param signalData 信号数据的Map对象
     * @param condition 预警规则中的条件字符串
     * @return 条件是否成立
     */
    public static boolean evaluateCondition(Map<String, Object> signalData, String condition) {
        condition = condition.replace(" ", "");
        String[] tokens = condition.split("<=|<|>|>=");

        double rightValue;
        if (tokens[1].equals("Mx-Mi") || tokens[0].equals("Mx-Mi")) {
            double Mx = (double) signalData.getOrDefault("Mx", Double.NaN);
            double Mi = (double) signalData.getOrDefault("Mi", Double.NaN);
            rightValue = Mx - Mi;
        } else if (tokens[1].equals("Ix-Ii") || tokens[0].equals("Ix-Ii")) {
            double Ix = (double) signalData.getOrDefault("Ix", Double.NaN);
            double Ii = (double) signalData.getOrDefault("Ii", Double.NaN);
            rightValue = Math.abs(Ix - Ii);
        } else {
            return false;
        }

        double leftValue = Double.parseDouble(tokens[0]);

        if (condition.contains("<=")) {
            return leftValue <= rightValue;
        } else if (condition.contains("<")) {
            return leftValue < rightValue;
        }

        return false;
    }


}

